require('./static/css/pure.css');
require('./css/album3.css');
var jQuery = require('jquery');
var $ = jQuery;

function component() {
    var ulCarouselList = document.createElement("ul");
    ulCarouselList.id = "album-carousel-list";
    ulCarouselList.className = "album-carousel-list";
    for (var i = 0; i < 9; i++) {
        var liThumb = document.createElement("li");
        liThumb.className = "album-carousel-thumb";
        var aThumb = document.createElement("a");
        aThumb.href = "./static/pics/0000" + (i + 1) + ".jpg";
        var imgThumb = document.createElement("img");
        imgThumb.src = "./static/pics/0000" + (i + 1) + ".jpg";
        imgThumb.alt = "相册图片-示例图片（" + (i + 1) + "）";
        imgThumb.width = 230;
        imgThumb.height = 144;
        aThumb.appendChild(imgThumb);
        liThumb.appendChild(aThumb);
        if (i === 0) {
            liThumb.className = "album-carousel-thumb album-carousel-thumb-selected";
        }
        ulCarouselList.appendChild(liThumb);
    }
	for (var i = 9; i < 20; i++) {
        var liThumb = document.createElement("li");
        liThumb.className = "album-carousel-thumb";
        var aThumb = document.createElement("a");
        aThumb.href = "./static/pics/000" + (i + 1) + ".jpg";
        var imgThumb = document.createElement("img");
        imgThumb.src = "./static/pics/000" + (i + 1) + ".jpg";
        imgThumb.alt = "相册图片-示例图片（" + (i + 1) + "）";
        imgThumb.width = 230;
        imgThumb.height = 144;
        aThumb.appendChild(imgThumb);
        liThumb.appendChild(aThumb);
        if (i === 0) {
            liThumb.className = "album-carousel-thumb album-carousel-thumb-selected";
        }
        ulCarouselList.appendChild(liThumb);
    }
    return ulCarouselList;
}

document.getElementById('album-carousel-zone').appendChild(component());;

/**
 * Album
 */
(function ($) {
    var CLS_SELECTED = "album-carousel-thumb-selected",
        CLS_HIDE = "hide",
        PX = "px";
    jQuery.Album = function (config) {
        this.setting = {
            root: $("#album-image-md"),
            image: $("#album-image"),
            title: $("#album-image-ft"),
            btnDownload: $("#album-download"),
            navBlock: $("#album-image-nav"),
            btnPrev: $("#album-image-btn-prev"),
            btnNext: $("#album-image-btn-next"),
            prevBlock: $("#album-image-nav-left-block"),
            nextBlock: $("#album-image-nav-right-block"),
            overlay: $("#album-image-loading-overlay"),
            Carousel: new jQuery.Carousel({
                root: '#album-carousel',
                carousel: '#album-carousel-list',
                pages: {
                    prev: '#album-carousel-btn-prev',
                    next: '#album-carousel-btn-next'
                },
                direction: 'H'
            }),
            curIndex: 0,
            maxWidth: 1000,
            maxHeight: 750
        };
        $.extend(this.setting, config);
        this.selectedItem = null;
        this.currentItem = null;
        this.isloading = false;
        this.init();
        return this;
    };
    jQuery.Album.prototype = {
        init: function () {
            this.select().change().bindEvent();
            return this;
        },
        change: function () {
            var Album = this,
                currentItem = Album.currentItem,
                image = Album.getImage(),
                title = Album.getTitle(),
                overlay = Album.getOverlay(),
                btnDownload = Album.getBtnDownload(),
                src = currentItem.find("a:first").attr("href"),
                alt = currentItem.find("img:first").attr("alt"),
                percent = 0,
                preloader = new Image();
            overlay.removeClass(CLS_HIDE);
            this.isloading = true;
            preloader.src = src;
            $(preloader).load(function (evt) {
                var width = preloader.width,
                    height = preloader.height,
                    maxWidth = Album.getMaxWidth(),
                    maxHeight = Album.getMaxHeight();
                percent = width / height;
                if (width > maxWidth) {
                    width = maxWidth;
                    height = width / percent;
                    if (height > maxHeight) {
                        percent = maxHeight / height;
                        width = width * percent;
                        height = maxHeight;
                    }
                } else {
                    if (width <= maxWidth) {
                        if (height > maxHeight) {
                            percent = maxHeight / height;
                            width = width * percent;
                            height = maxHeight;
                        }
                    }
                }
                image.animate({
                    "width": width + PX,
                    "height": height + PX,
                    "margin-left": -(width / 2) + PX,
                    "margin-top": -(height / 2) + PX
                }, 500, function () {
                    image.attr({
                        "src": src,
                        "alt": alt
                    });
                    title.html(alt);
                    btnDownload.attr("href", src);
                    overlay.addClass(CLS_HIDE);
                    Album.isloading = false;
                });
            });
            return this;
        },
        select: function () {
            var selectedItem = this.selectedItem,
                currentItem = null,
                items = this.getItems(),
                curIndex = this.getCurrentIndex();
            if (selectedItem) {
                selectedItem.removeClass(CLS_SELECTED);
            }
            currentItem = this.currentItem = $(items[curIndex]);
            currentItem.addClass(CLS_SELECTED);
            this.selectedItem = currentItem;
            return this;
        },
        prev: function () {
            this.setCurrentIndex(this.getCurrentIndex() - 1);
            if (this.getCurrentIndex() < 0) {
                this.setCurrentIndex(this.getLength() - 1).prevGroup();
            } else {
                if (this.getCurrentIndex() > 0) {
                    if (this.getCurrentIndex() < this.getCurrentPage() * this.getItemsPrePage()) {
                        this.prevGroup();
                    }
                }
            }
            this.select().change();
            return this;
        },
        next: function () {
            this.setCurrentIndex(this.getCurrentIndex() + 1);
            if (this.getCurrentIndex() > this.getLength() - 1) {
                this.setCurrentIndex(0).nextGroup();
            } else {
                if (this.getCurrentPage() < this.getMaxPages()) {
                    if (this.getCurrentIndex() > ((this.getCurrentPage() + 1) * this.getItemsPrePage()) - 1) {
                        this.nextGroup();
                    }
                }
            }
            this.select().change();
            return this;
        },
        prevGroup: function () {
            var Carousel = this.getCarousel();
            Carousel.prev();
            return this;
        },
        nextGroup: function () {
            var Carousel = this.getCarousel();
            Carousel.next();
            return this;
        },
        bindEvent: function () {
            var Album = this,
                root = Album.getRoot(),
                navBlock = Album.getNavBlock(),
                prevBlock = Album.getPrevBlock(),
                nextBlock = Album.getNextBlock(),
                btnPrev = Album.getBtnPrev(),
                btnNext = Album.getBtnNext(),
                items = Album.getItems();
            root.hover(function () {
                navBlock.removeClass(CLS_HIDE);
            }, function () {
                navBlock.addClass(CLS_HIDE);
            });
            prevBlock.click(function (evt) {
                Album.prev();
                evt.preventDefault();
                evt.stopPropagation();
            });
            nextBlock.click(function (evt) {
                Album.next();
                evt.preventDefault();
                evt.stopPropagation();
            });
            btnPrev.click(function (evt) {
                Album.prev();
                evt.preventDefault();
                evt.stopPropagation();
            });
            btnNext.click(function (evt) {
                Album.next();
                evt.preventDefault();
                evt.stopPropagation();
            });
            items.each(function (i, item) {
                $(item).click(function (evt) {
                    if (!$(this).hasClass(CLS_SELECTED) && !Album.isLoading) {
                        Album.setCurrentIndex(i).select().change();
                    }
                    evt.preventDefault();
                    evt.stopPropagation();
                });
            });
            return this;
        },
        getRoot: function () {
            return $(this.setting.root);
        },
        getImage: function () {
            return $(this.setting.image);
        },
        getTitle: function () {
            return $(this.setting.title);
        },
        getBtnDownload: function () {
            return $(this.setting.btnDownload);
        },
        getNavBlock: function () {
            return $(this.setting.navBlock);
        },
        getPrevBlock: function () {
            return $(this.setting.prevBlock);
        },
        getNextBlock: function () {
            return $(this.setting.nextBlock);
        },
        getBtnPrev: function () {
            return $(this.setting.btnPrev);
        },
        getBtnNext: function () {
            return $(this.setting.btnNext);
        },
        getOverlay: function () {
            return $(this.setting.overlay);
        },
        getCarousel: function () {
            return this.setting.Carousel;
        },
        getCurrentPage: function () {
            var Carousel = this.getCarousel();
            return Carousel.setting.curPage;
        },
        setCurrentPage: function (page) {
            var Carousel = this.getCarousel();
            Carousel.setting.curPage = page;
            return this;
        },
        getMaxPages: function () {
            var Carousel = this.getCarousel();
            return Carousel.setting.maxPages;
        },
        getItemsPrePage: function () {
            var Carousel = this.getCarousel();
            return Carousel.setting.itemsPrePage;
        },
        getItems: function () {
            return this.getSamples();
        },
        getSamples: function () {
            var Carousel = this.getCarousel();
            return Carousel.setting.items;
        },
        getLength: function () {
            return this.getItems().length;
        },
        getCurrentIndex: function () {
            return this.setting.curIndex;
        },
        setCurrentIndex: function (i) {
            this.setting.curIndex = i;
            return this;
        },
        getMaxWidth: function () {
            return this.setting.maxWidth;
        },
        getMaxHeight: function () {
            return this.setting.maxHeight;
        }
    };
})(jQuery);

/**
 * Carousel
 */
jQuery.Carousel = function (config) {
    this.setting = {
        root: null,
        related: null,
        relatedlist: null,
        relateditems: null,
        carousel: null,
        pages: {
            prevBlock: null,
            nextBlock: null,
            prev: null,
            next: null,
            current: null,
            total: null
        },
        timer: null,
        curPage: 0,
        maxPages: 0,
        speed: 1000,
        item: 'li',
        items: null,
        itemsPrePage: 0,
        itemsPreStep: 0,
        direction: 'V',
        auto: false,
        isButtonsOut: false
    };
    $.extend(this.setting, config);
    this.init();
    return this;
};
jQuery.Carousel.prototype = {
    init: function () {
        var Carousel = this,
            setting = Carousel.setting,
            direction = setting.direction.toUpperCase(),
            carousel = setting.carousel,
            carouselWidth = 0,
            pages = setting.pages,
            next = pages.next,
            prev = pages.prev,
            related = setting.related,
            relatedlist = setting.relatedlist,
            current = pages.current,
            total = pages.total,
            maxPages = 0;
        this.deleteItems();
        setting.items = $(carousel).find(setting.item);
        if (!setting.itemsPreStep) {
            setting.itemsPrePage = $(carousel).parent().width() / $(setting.items[0]).width();
            maxPages = setting.maxPages = Math.ceil($(setting.items).length / setting.itemsPrePage);
        } else {
            if (setting.itemsPreStep > 0) {
                if ($(setting.items).length < setting.itemsPrePage) {
                    maxPages = setting.maxPages = 1;
                } else {
                    maxPages = setting.maxPages = 1 + Math.ceil(($(setting.items).length - setting.itemsPrePage) / setting.itemsPreStep);
                }
            }
        }
        if (maxPages < 2) {
            $(next).addClass('hide');
            $(prev).addClass('hide');
        }
        if (direction === 'H') {
            $(carousel).css('width', ($(setting.items[0]).width() * setting.items.length) + 'px');
        }
        if (related && relatedlist) {
            setting.relateditems = $(relatedlist).find('li');
        }
        if (current) {
            $(current).html(setting.curPage + 1);
        }
        if (total) {
            $(total).html(maxPages);
        }
        this.bind();
        if (setting.auto) {
            setting.timer = setTimeout(function () {
                Carousel.auto.call(Carousel);
            }, 4000);
        }
        return this;
    },
    bind: function () {
        var Carousel = this,
            setting = this.setting,
            root = $(setting.root),
            related = setting.related,
            relateditems = setting.relateditems,
            pages = setting.pages,
            prevBlock = pages.prevBlock,
            nextBlock = pages.nextBlock,
            btnNext = $(root.find(pages.next)[0]),
            btnPrev = $(root.find(pages.prev)[0]),
            clearTimer = function (evt) {
                if (setting.timer) {
                    clearTimeout(setting.timer);
                    setting.timer = null;
                }
            },
            setTimer = function (evt) {
                setting.timer = setTimeout(function () {
                    Carousel.auto.call(Carousel);
                }, 4000);
            };
        if (setting.auto) {
            $(root).mouseover(clearTimer);
            $(root).mouseout(setTimer);
            if (setting.isButtonsOut) {
                btnNext.mouseover(clearTimer);
                btnNext.mouseout(setTimer);
                btnPrev.mouseover(clearTimer);
                btnPrev.mouseout(setTimer);
            }
        }
        if (prevBlock && nextBlock) {
            root.mouseover(function () {
                $(btnPrev).removeClass('hide');
                $(btnNext).removeClass('hide');
            });
            root.mouseout(function () {
                $(btnPrev).addClass('hide');
                $(btnNext).addClass('hide');
            });
            $(prevBlock).click(function (evt) {
                Carousel.prev.call(Carousel);
                evt.preventDefault();
                evt.stopPropagation();
            });
            $(nextBlock).click(function (evt) {
                Carousel.next.call(Carousel);
                evt.preventDefault();
                evt.stopPropagation();
            });
        }
        $(btnPrev).click(function (evt) {
            Carousel.prev.call(Carousel);
            evt.preventDefault();
            evt.stopPropagation();
        });
        $(btnNext).click(function (evt) {
            Carousel.next.call(Carousel);
            evt.preventDefault();
            evt.stopPropagation();
        });
        if (related) {
            $(relateditems).hover(function (evt) {
                $(this).addClass('hover');
            }, function (evt) {
                $(this).removeClass('hover');
            });
            $('#lnk-back-beginning').click(function (evt) {
                setting.curPage = 0;
                Carousel.current.call(Carousel, setting.curPage);
                $(related).addClass('hide');
                evt.preventDefault();
                evt.stopPropagation();
            });
        }
        return this;
    },
    next: function () {
        var setting = this.setting,
            pages = setting.pages,
            related = setting.related,
            current = pages.current,
            total = pages.total,
            maxPages = setting.maxPages;
        setting.curPage += 1;
        if (setting.curPage === maxPages) {
            if (!related) {
                setting.curPage = 0;
            }
        }
        if (related) {
            if (setting.curPage === maxPages) {
                $(related).removeClass('hide');
            } else {
                this.current(setting.curPage);
            }
        } else {
            this.current(setting.curPage);
        }
        return this;
    },
    prev: function () {
        var setting = this.setting,
            pages = setting.pages,
            current = pages.current,
            total = pages.total,
            maxPages = setting.maxPages;
        setting.curPage -= 1;
        if (setting.curPage < 0) {
            setting.curPage = maxPages - 1;
        }
        this.current(setting.curPage);
        return this;
    },
    current: function (index) {
        var carousel = this,
            setting = this.setting,
            pages = setting.pages,
            current = pages.current,
            total = pages.total,
            maxPages = setting.maxPages;
        if (current) {
            $(current).html(setting.curPage + 1);
        }
        if (total) {
            $(total).html(maxPages);
        }
        this.move(setting.curPage);
        return this;
    },
    move: function (index) {
        var setting = this.setting,
            direction = setting.direction,
            carousel = $(setting.carousel);
        if (direction.toUpperCase() === 'H') {
            property = 'left';
            scrollValue = setting.itemsPreStep ? (setting.itemsPreStep * $(setting.items[0]).width()) * index : (setting.itemsPrePage ? (setting.itemsPrePage * $(setting.items[0]).width()) * index : $(setting.root).width() * index);
            carousel.animate({
                'left': '-' + scrollValue + 'px'
            }, setting.speed);
        } else {
            if (direction.toUpperCase() === 'V') {
                scrollValue = setting.itemsPreStep ? (setting.itemsPreStep * $(setting.items[0]).height()) * index : $(setting.root).height() * index;
                carousel.animate({
                    'top': '-' + scrollValue + 'px'
                }, setting.speed);
            }
        }
        return this;
    },
    deleteItems: function () {
        var listPhotos = $(this.setting.carousel).find('img');
        if (listPhotos.length === 0) {
            return false;
        }
        listPhotos.each(function (i, img) {
            if ($(img).attr('src').indexOf('.jpg') === -1) {
                $(img).parent().remove();
            }
        });
        return this;
    },
    auto: function () {
        var Carousel = this,
            setting = this.setting;
        if (setting.timer) {
            clearTimeout(setting.timer);
            setting.timer = null;
        }
        if (setting.maxPages < 2) {
            return false;
        }
        setting.curPage += 1;
        if (setting.curPage === setting.maxPages) {
            setting.curPage = 0;
        }
        this.current(setting.curPage);
        setting.timer = setTimeout(function () {
            Carousel.auto.call(Carousel);
        }, 4000);
        return this;
    }
};
jQuery.carousels = function () {
    var carousels = [],
        i = 0,
        len = arguments.length;
    for (; i < len; i += 1) {
        carousels[i] = new jQuery.Carousel(arguments[i]);
    }
    return carousels;
};

var Album = new jQuery.Album();